import pinia from "@/store";
import { storeToRefs } from "pinia";
import { Page } from "@/store/page";
import { User } from "@/store/user";
import { getGameUrl } from "./useNetMethods";
import { Session } from "./storage";
// import router from "@/router";
const { settings } = storeToRefs(Page(pinia));
const {
    lang
} = storeToRefs(Page(pinia));
const { roleInfo, currencyRate, hasLogin } = storeToRefs(User(pinia));
export function get<T>(url: string): Promise<T> {
    return new Promise((resole, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    let res = JSON.parse(xhr.responseText);
                    resole(res);
                } else {
                    reject(`get: ${url} err`);
                }
            }
        };
        xhr.onerror = (err) => {
            reject(err);
        };

        xhr.open("GET", url, true);

        xhr.timeout = 2000;
        xhr.send();
    });
}
/** 解析名称
 *
 * */
export const unserialize = (v: any, isPlatform: boolean) => {
    if (!v) return '';
    let obj: any = {
        'en-US': 'en-US',
        en: 'en-US',
        'en-AU': 'en-US',
        zh: 'zh-CN',
        'zh-CN': 'zh-CN',
        vi: 'vi-VN',
        'vi-VN': 'vi-VN',
        vn: 'vi-VN'
    };
    if (isPlatform) {
        v = JSON.parse(v);
    }
    return v[obj[lang.value]];
};
/**
  * 取最快的链接
  */
export const getFastestUrl = (): Promise<string> => {
    return new Promise(async (resolve) => {
        function determineProtocol(ipAddress: string) {
            if (ipAddress.startsWith("http://")) {
                return "http";
            } else if (ipAddress.startsWith("https://")) {
                return "https";
            } else if (ipAddress.startsWith("ws://")) {
                return "ws";
            } else if (ipAddress.startsWith("wss://")) {
                return "wss";
            } else {
                // 默认使用 http 协议
                return "http";
            }
        }

        function connectWithTimeout(url: string | URL, timeout: number | undefined) {
            return new Promise<void>((resolve, reject) => {
                const ws = new WebSocket(url);

                const timer = setTimeout(() => {
                    reject(new Error("WebSocket 连接超时"));
                    ws.close();
                }, timeout);

                ws.onopen = function () {
                    clearTimeout(timer);
                    ws.close();
                    resolve();
                };

                ws.onerror = function (error) {
                    clearTimeout(timer);
                    reject(error);
                };
            });
        }

        //暂时注释掉选择速度最快的服务器
        let fastCost = 99999;
        let fastIndex = 0;
        let fastUrl = Session.get('fastUrl')
        if (fastUrl) {
            resolve(fastUrl)
        } else {
            if (settings.value.server_testUrls.length > 0) {
                let promises: Promise<{ cost: number; index: number }>[] = settings.value.server_testUrls.map((urls: any[], index: any) => {
                    let url = urls[0];
                    return new Promise((resolve) => {
                        let startTime = new Date().getTime();
                        let _nowrul = urls[0]; // httpToWs(url);

                        switch (determineProtocol(_nowrul)) {
                            case "http":
                            case "https":
                                {
                                    get(url)
                                        .then(() => {
                                            let endTime = new Date().getTime();
                                            let cost = endTime - startTime;
                                            console.log(`请求:${url} 耗时:${cost}`);
                                            resolve({ cost, index });
                                        })
                                        .catch((error: any) => {
                                            console.error("Error:", error);
                                            resolve({ cost: 9999999, index }); // 如果出错，将 cost 设置为 Infinity
                                        });
                                }
                                break;
                            case "ws":
                            case "wss":
                                {
                                    connectWithTimeout(_nowrul, 5000)
                                        .then(() => {
                                            // console.log('WebSocket 连接成功');
                                            let endTime = new Date().getTime();
                                            let cost = endTime - startTime;
                                            console.log(`请求:${_nowrul} 耗时:${cost}`);
                                            resolve({ cost, index });
                                        })

                                        .catch((error) => {
                                            console.error("WebSocket 连接失败:", error);
                                            resolve({ cost: 9999999, index }); // 如果出错，将 cost 设置为 Infinity
                                        });
                                }
                                break;

                            default:
                                break;
                        }
                    });
                });
                Promise.all(promises).then(async (results) => {
                    results.forEach(({ cost, index }) => {
                        if (cost < fastCost) {
                            fastCost = cost;
                            fastIndex = index;
                        }
                    });

                    let fastestUrl = settings.value.server_testUrls[fastIndex];
                    // let _wsurl = fastestUrl[1]; //httpToWs(fastestUrl);
                    // let server_ips = [_wsurl];
                    console.log(`最快URL:${fastestUrl[0]} 耗时:${fastCost}`);
                    resolve(fastestUrl[1])
                    Session.set('fastUrl', fastestUrl[1])
                    // Local.set('fastestUrlKey', fastestUrl[0])
                    // StorageMgr.instance.set(this.fastestUrlKey, fastestUrl[0]);
                    // let _ip = Local.get("lastLoginIP");
                    // if (_ip) {
                    //     server_ips.unshift(_ip);
                    // }

                    // GlobalData.getRemoteJson(resolve);
                });
            } else {
                resolve(settings.value.server_testUrls[0][1])
            }
        }
    });
}
// 玩家IP
export const IP = (): Promise<string> => {
    return new Promise(async (resolve) => {
        let fastCost = 99999;
        let fastIndex = 0;
        let _ip = "";
        let promises: Promise<{ cost: number; index: number; str: string }>[] = settings.value.GET_IP_LIST.map((url: any, index: any) => {
            return new Promise((resolve) => {
                let startTime = new Date().getTime();

                let xhr = new XMLHttpRequest();
                xhr.open("GET", url, true);
                xhr.timeout = 5000;
                xhr.responseType = "text";

                xhr.onreadystatechange = function () {
                    if (xhr.readyState === XMLHttpRequest.DONE) {
                        if (xhr.status === 200) {
                            let endTime = new Date().getTime();
                            let cost = endTime - startTime;
                            let str: any = xhr.responseText;
                            // cc.log(请求:${url} 耗时:${cost}, index:${index}, str);
                            resolve({ cost, index, str });
                        } else {
                            // console.error("Error: xhr.status", xhr.status);
                            resolve({ cost: 9999999, index, str: '' }); // 如果出错，将 cost 设置为 Infinity
                        }
                    }
                };

                xhr.send();
            });
        });

        Promise.all(promises).then((results) => {
            results.forEach(({ cost, index, str }) => {
                if (cost < fastCost) {
                    fastCost = cost;
                    fastIndex = index;
                    _ip = str;
                }
            });
            let fastestUrl = settings.value.GET_IP_LIST[fastIndex];
            console.log(`最快IP: ${fastestUrl} 耗时: ${fastCost} IP: ${_ip}`);
            resolve(_ip);
        });
    });
}

// convert the display money, all the money need to call this function before display
export const convert2DisplayMoney = (num: number, isShowDecimal: boolean = false, isToLocal: boolean = true) => {
    if (typeof num == "string") {
        num = Number(num);
    }
    num = isShowDecimal
        ? Number((num / (hasLogin.value ? roleInfo.value.currencyrate : currencyRate.value)).toFixed(0))
        : Number((num / (hasLogin.value ? roleInfo.value.currencyrate : currencyRate.value)).toFixed());
    let result;
    if (isToLocal) result = num.toLocaleString();
    else result = num;
    return result;
}
// for the input money and need to send to server
export const convert2ServerMoney = (num: number) => {
    return num * roleInfo.value.currencyrate;
}

export const onPlayGame = async (v: any) => {

    if (!hasLogin.value) {
        await User(pinia).setLogin(true)
        return
    }
    // 侧滑页面有打开的话要关闭
    // if (showLeft.value) {
    //     showLeft.value = false 
    // }
    let langObj: any = {
        'en-US': 3,
        'vi-VN': 2,
        'zh-CN': 1
    }

    console.log(v, langObj[lang.value], Page(pinia));
    // router.push({
    //     path:"/game",
    // })
    if (v.agentId == 30) {
        v.kindId = '7'
    }
    getGameUrl(v, langObj[lang.value], Page(pinia))

}
// 未登录汇率
export const handleCurrencyRate = async (data: any) => {
    console.log("汇率", data);
    await User(pinia).getCurrencyRate(data);
};
// 绑定资金密码后，需要更新 store
export const updateStorePayPwd = async (val: any) => {
    const newData = { ...roleInfo.value };
    newData.withdraw_pwd = val;
    newData.withdraw_pwd_status = 2; // 已绑定资金密码
    await User(pinia).getRoleInfo(newData);
}
// 获取ip对应得地址 保存到session中
export const getIPAddress = async (data: any) => {
    let ips = Session.get('ips') || {}
    for (let index = 0; index < data.length; index++) {
        if (data[index].ip && !ips[data[index].ip]) {
            let response = await fetch(settings.value.geoip_api + data[index].ip)
            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            let res = await response.json()
            if (res && res.data && res.data.country) {
                ips[data[index].ip] = `${res.data.city} ${res.data.region} ${res.data.country}`
                data[index].location = `${res.data.city} ${res.data.region} ${res.data.country}`
                Session.set('ips', ips)
            } else {

            }

        } else {
            data[index].location = ips[data[index].ip]
        }
    }
}